import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import moment from 'moment';
import { message } from 'antd'
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = path => reg.test(path);
export const isAntDesignPro = () => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }

  return window.location.hostname === 'preview.pro.ant.design';
}; // 给官方演示站点用，用于关闭真实开发环境不需要使用的特性

export const isAntDesignProOrDev = () => {
  const { NODE_ENV } = process.env;

  if (NODE_ENV === 'development') {
    return true;
  }

  return isAntDesignPro();
};
export const getPageQuery = () => parse(window.location.href.split('?')[1]);
/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */

export const getAuthorityFromRouter = (router = [], pathname) => {
  const authority = router.find(
    ({ routes, path = '/' }) =>
      (path && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname)),
  );
  if (authority) return authority;
  return undefined;
};

export const getRouteAuth = (path, routeData) => {
  return routeData.some(route => {
    if (route.path === path) {
      return true;
    } else if (route.containPath && ~route.containPath.split(';').indexOf(path)) {
      return true;
    } else if (route.children) {
      return getRouteAuth(path, route.children);
    } else {
      return false;
    }
  });
};

export const getComponentAuth = (code, permissions) => {
  return permissions[code];
};
export const getItemWithCompare = (compare, value, data) => {
  let res = {};
  data.every(item => {
    const compared =
      typeof compare === 'function'
        ? compare(item, value)
        : compare.every(func => func(item, value));
    if (compared) {
      res = item;
      return false;
    } else {
      if (item.children) {
        res = getItemWithCompare(compare, value, item.children);
        return Object.keys(res).length === 0;
      } else {
        return true;
      }
    }
  });
  return res;
};

const PAGE_TYPE = '1';
const MENU_TYPE = '2';
export const getPageItemByPath = (path, menuData) => {
  const comparePath = (item, value) => item && item.path === value;
  const compareContainPath = (item, value) => item && item.containPath && ~item.containPath.split(';').indexOf(value);
  const comparePageType = (item, _) => item && item.type === PAGE_TYPE;
  const compareMenuType = (item, _) => item && item.type === MENU_TYPE;
  const compares = (item, value) => comparePath(item, value) || compareContainPath(item, value);

  const findPageItem = getItemWithCompare([compares, comparePageType], path, menuData);
  if (findPageItem.id) {
    return findPageItem;
  }

  const findMenuItem = getItemWithCompare([compares, compareMenuType], path, menuData);

  if (findMenuItem.children && findMenuItem.children.length > 0) {
    return getPageItemByPath(findMenuItem.children[0].path, findMenuItem.children);
  }

  return {};
};

export const getPageItemById = (id, menuData) => {
  const compareId = (item, value) => item && item.id === value;
  return getItemWithCompare(compareId, id, menuData);
};

export const getParentMenuByPage = (page, menuData) => {
  const compareId = (item, value) => item && item.id === value;
  return getItemWithCompare(compareId, page.pid, menuData);
};

// < 3h : n小时前 / n分钟前
// >= 3h < 1d : hh:mm
// >1d < 2d : 昨天
// < 1y : mm-dd hh:mm
// >= 1y : yyyy-mm-dd
export const formatMoment = function formatMoment(date) {
  const yearEq = moment(date).year() === moment().year();
  const dayEq = moment(date).dayOfYear() === moment().dayOfYear();
  const dayAgoEq =
    moment(date).format('YYYYMMDD') ===
    moment()
      .subtract(1, 'd')
      .format('YYYYMMDD');
  const hour3Ago =
    moment(date)
      .add(3, 'h')
      .valueOf() > Date.now();

  switch (true) {
    case hour3Ago:
      return moment(date).fromNow();
    case yearEq && dayEq:
      return moment(date).format('HH:mm');
    case dayAgoEq:
      return moment(date).format('[昨天] HH:mm');
    case yearEq:
      return moment(date).format('MM[月] DD[日] HH:mm');
    default:
      return moment(date).format('YYYY[年] MM[月] DD[日]');
  }
};

export const phoneNumFormat = function phoneNumFormat(num) {
  if (!num) {
    return '';
  }
  return ''.replace
    .call(num, /^([0-9]{3})([^\s]+)$/, '$1 $2')
    .replace(/([0-9]{4})(?=[0-9])/g, '$1 ');
};

/**
 * 根据秒数返回（天，小时，分钟，秒），秒以上的时间为空，则不展示该时间段
 * 示例：1天2时3分4秒，5分6秒
 */
export const intervalTime = ($time) => {
  //计算天
  let $days = ($time >= 86400) ? Math.floor($time / 86400) : 0;
  //计算小时
  var $temp = $time - 86400 * $days;
  let $hour = ($temp >= 3600 && $temp < 86400) ? Math.floor($temp / 3600) : 0;
  //计算分钟
  $temp = $time - 86400 * $days - 3600 * $hour;
  let $minute = ($temp >= 60 && $temp < 3600) ? Math.floor($temp / 60) : 0;
  //计算秒
  $temp = $time - 86400 * $days - 3600 * $hour - 60 * $minute;
  let $second = ($temp > 0 && $temp < 60) ? $temp : 0;
  // let $result = `${$days ? `${$days}天` : ''}
  //   ${$hour ? `${$hour}时` : ''}
  //   ${$minute ? `${$minute}分` : ''}
  //   ${$second}秒`
  let $result = `${$days}天 ${$hour}时 ${$minute}分 ${$second}秒`
  return $result;
}

/**
 * 
 * @param {Blob} blobData //blob数据
 * @param {String} fileName //文件名
 */
export const exportExcel = (blobData, fileName, suffix = '.CSV') => {
  let blob = new Blob([blobData], {
    type:
      'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  });
  let downloadElement = document.createElement('a');
  let nowTime = moment(Date.now()).format('YYYY-MM-DD HH_ss_mm');
  let lastFileName = `${fileName}${nowTime}${suffix}`;
  let href = window.URL.createObjectURL(blob);
  document.body.appendChild(downloadElement);
  downloadElement.href = href;
  //兼容IE
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    downloadElement.addEventListener('click', () => {
      window.navigator.msSaveOrOpenBlob(blob, lastFileName)
    })
  } else {
    downloadElement.download = lastFileName
  }
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement)
  message.loading('正在导出');
  window.URL.revokeObjectURL(href) //释放掉blob对象
}

/**
 * 
 * @param {String} val 航班号
 */
export const formatFlightNo = (val) => {
  if (!val) {
    return '';
  } else if (val.length < 3 || /^\D/.test(val)) {
    return ''.toUpperCase.call(val);
  } else if (/^\d{2}/.test(val)) {
    return `3U${val}`;
  } else {
    return val;
  }
}

/**
 * //转换为formData对象
 * @param {Object} msg 参数
 */
 export const fomatFormData = (msg) => {
  let params = new URLSearchParams();
  for (let key in msg) {
    params.append(key, msg[key])
  }
  return params;
}